package com.grm.handler;

import com.grm.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.StringJoiner;

/**
 * 自定义全局异常捕获
 *
 * @author gaorimao
 */
@RestControllerAdvice(annotations = RestController.class)
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 全局异常捕捉处理
     *
     * @param e 异常
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public Result errorHandler(HttpServletRequest req, Exception e) {
        return Result.failed(500, e.getMessage());
    }

    /**
     * request url参数校验，异常
     * @param e
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Result constraintViolationExceptionException(ConstraintViolationException e) {
        List<String> messages = new ArrayList<>();
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        for (ConstraintViolation<?> constraintViolation : constraintViolations) {
            String message = constraintViolation.getMessage();
            Path propertyPath = constraintViolation.getPropertyPath();
            String errorField = "";
            for (Path.Node node : propertyPath) {
                errorField = node.getName();
            }
            message = errorField+":"+message;
            messages.add(message);
        }
        return Result.failed(500, String.join(",",messages));
    }

    /**
     * post请求body体参数校验，异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidException(MethodArgumentNotValidException e) {
        // 将所有的错误提示使用";"拼接起来并返回
        StringJoiner sj = new StringJoiner(";");
        //name:不能为空;password:长度不能小于4
        e.getBindingResult().getFieldErrors().forEach(x -> sj.add(x.getField()+":"+x.getDefaultMessage()));
        return Result.failed(500, sj.toString());
    }

    /**
     * 缺少body请求体异常处理器
     *
     * @param e 缺少请求体异常
     * @return ResponseResult
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result parameterBodyMissingExceptionHandler(HttpMessageNotReadableException e) {
        return Result.failed(500, "body请求体不能为空!");
    }

    /**
     * 忽略参数异常处理器
     *
     * @param e 忽略参数异常
     * @return ResponseResult
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Result parameterMissingExceptionHandler(MissingServletRequestParameterException e) {
        return Result.failed(500, "请求参数"+e.getParameterName()+"不能为空!");
    }
}
